package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Value("classpath:template/运营数据报表模板.xlsx")
    private Resource templateResource;
    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用来存放从begin到end的每天的营业额日期
        ArrayList<LocalDate> dateArrayList = new ArrayList<>();
        dateArrayList.add(begin);
        //循环从开始日期到结束日期，将日期添加到集合中
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateArrayList.add(begin);
        }
        //将日期集合转化为字符串，以逗号分隔
        String dateListString = StringUtils.join(dateArrayList, ",");
        //根据日期范围查询对应的营业额
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateArrayList) {
            //把日期转化为时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将查询条件封装到map中
            HashMap<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            //查询营业额
            Double turnover=orderMapper.sumByMap(map);
            if (turnover==null){
                turnover=0.0;
            }
            turnoverList.add(turnover);
        }
        //将营业额集合转化为字符串，以逗号分隔
        String turnoverListString = StringUtils.join(turnoverList, ",");
        //封装到VO中
        return TurnoverReportVO
                .builder()
                .dateList(dateListString)
                .turnoverList(turnoverListString)
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //当前集合用来存放从begin到end的每天的用户日期
        ArrayList<LocalDate> dateArrayList = new ArrayList<>();
        dateArrayList.add(begin);
        //循环从开始日期到结束日期，将日期添加到集合中
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateArrayList.add(begin);
        }
        //将日期集合转化为字符串，以逗号分隔
        String dateListString = StringUtils.join(dateArrayList, ",");
        //存放新增用户和总用户
        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalList = new ArrayList<>();
        for (LocalDate date : dateArrayList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            HashMap<String, Object> totalMap = new HashMap<>();
            HashMap<String, Object> newMap = new HashMap<>();
            newMap.put("end", endTime);
            newMap.put("begin", beginTime);
            totalMap.put("end", beginTime);
            Integer newlUser = userMapper.countByMap(newMap);
            Integer totalUser = userMapper.countByMap(totalMap);
            if (newlUser==null){
                newlUser=0;
            }
            if (totalUser==null){
                totalUser=0;
            }
            totalList.add(totalUser);
            newUserList.add(newlUser);
        }
        String totalListString = StringUtils.join(totalList, ",");
        String newUserListString = StringUtils.join(newUserList, ",");
        return UserReportVO
                .builder()
                .dateList(dateListString)
                .newUserList(newUserListString)
                .totalUserList(totalListString)
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateTimeList = new ArrayList<>();
        ArrayList<Integer> totalOrderCounts = new ArrayList<>();
        ArrayList<Integer> validOrderCounts = new ArrayList<>();

        dateTimeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }
        String dateStrings = StringUtils.join(dateTimeList, ",");
        for (LocalDate date : dateTimeList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询总订单数
            Integer totalOrderCount = getOrderCount(beginTime, endTime, null);
            if (totalOrderCount==null){
                totalOrderCount=0;
            }
            totalOrderCounts.add(totalOrderCount);

            //查询有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            if (validOrderCount==null){
                validOrderCount=0;
            }
            validOrderCounts.add(validOrderCount);

        }
        Integer totalOrderCountAll = getOrderCount(null, null, null);
        Integer validOrderCountAll = getOrderCount(null, null, Orders.COMPLETED);
        Double orderCompletionRate = validOrderCountAll / totalOrderCountAll.doubleValue();
        String totalOrderString = StringUtils.join(totalOrderCounts, ",");
        String validOrderString = StringUtils.join(validOrderCounts, ",");
        return OrderReportVO.builder()
                .dateList(dateStrings)
                .orderCountList(totalOrderString)
                .validOrderCountList(validOrderString)
                .totalOrderCount(totalOrderCountAll)
                .validOrderCount(validOrderCountAll)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.getSalesTop10(beginTime, endTime);
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : list) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        String nameListString = StringUtils.join(nameList, ",");
        String numberListString = StringUtils.join(numberList, ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameListString)
                .numberList(numberListString)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        //查询数据库获取30天营业数据：营业额、订单总数、有效订单数、订单完成率、
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        System.out.println(businessData);
        //读出模板数据
        InputStream inputStream = templateResource.getInputStream();
        XSSFWorkbook excel = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = excel.getSheet("Sheet1");
        sheet.getRow(1).getCell(1).setCellValue("时间"+dateBegin+"至"+dateEnd);
        XSSFRow row3 = sheet.getRow(3);
        row3.getCell(2).setCellValue(businessData.getTurnover());
        row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row3.getCell(6).setCellValue(businessData.getNewUsers());
        XSSFRow row4 = sheet.getRow(4);
        row4.getCell(2).setCellValue(businessData.getValidOrderCount());
        row4.getCell(4).setCellValue(businessData.getUnitPrice());

        // 遍历从 dateBegin 到 dateEnd 之间的所有日期（包括 dateBegin，不包括 dateEnd）
        Stream<LocalDate> dateStream = dateBegin.datesUntil(dateEnd.plusDays(1));
        final int[] rowIndex = {7};
        dateStream.forEach(date -> {
            // 在这里可以添加你需要的操作，例如查询数据库、写入文件等
            log.info("正在处理日期：{}", date);
            BusinessDataVO dataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow row = sheet.getRow(rowIndex[0]);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(dataVO.getTurnover());
            row.getCell(3).setCellValue(dataVO.getValidOrderCount());
            row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(dataVO.getUnitPrice());
            row.getCell(6).setCellValue(dataVO.getNewUsers());
            rowIndex[0]++;
        });


        //通知浏览器下载文件
        OutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.close();
        excel.close();



    }

    /**
     * 获取订单数量
     *
     * @param begin
     * @param end
     * @param status
     * @return 订单数量
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }


}
